package com.mall.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        //获取createOrderContext
        CreateOrderContext orderContext = (CreateOrderContext) context;

        //将购物车中商品id取出，给orderContext赋值
        List<CartProductDto> productDtoList = orderContext.getCartProductDtoList();
        ArrayList<Long> productIds = new ArrayList<>();
        for (CartProductDto cartProductDto : productDtoList) {

            Long productId = cartProductDto.getProductId();
            productIds.add(productId);
        }
        List<Long> buyProductIds = orderContext.getBuyProductIds();
        buyProductIds = productIds;

        //排序
        buyProductIds.sort(Long::compareTo);

        //锁定库存
        List<Stock> stocksForUpdate = stockMapper.findStocksForUpdate(buyProductIds);
        //判断查询出来的商品是否有问题
        if (CollectionUtils.isEmpty(stocksForUpdate)) {
            throw new BizException(OrderRetCode.PIPELINE_RUN_EXCEPTION.getCode(), "库存未初始化");
        }
        if (stocksForUpdate.size() != buyProductIds.size()) {
            throw new BizException(OrderRetCode.PIPELINE_RUN_EXCEPTION.getCode(), "部分商品初始化异常");
        }

        //扣减库存
        for (CartProductDto cartProductDto : productDtoList) {
            Long productId = cartProductDto.getProductId();
            //购买的数量
            Long productNum = cartProductDto.getProductNum();
            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setStockCount(-productNum);
            stock.setLockCount(productNum.intValue());
            int affectedRows = stockMapper.updateStock(stock);
            if(affectedRows == 0){
                throw new BizException(OrderRetCode.PIPELINE_RUN_EXCEPTION.getCode(), "库存不足");
            }
        }

        return true;
    }
}